<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"
	import="java.io.IOException,java.net.URL,sample.appsforyourdomain.AppsForYourDomainClient,com.google.gdata.client.appsforyourdomain.AppsForYourDomainService,com.google.gdata.client.appsforyourdomain.AppsForYourDomainQuery,com.google.gdata.client.appsforyourdomain.UserService,com.google.gdata.data.appsforyourdomain.provisioning.UserEntry,com.google.gdata.data.appsforyourdomain.provisioning.UserFeed,java.text.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> 
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Celestica Google Contacts</title>

<script language="JavaScript" type="text/javascript">
<!-- 
function changeNab(newPath){
	var curLoc = window.location.href;
	var newLoc = "";
	var pathLoc = curLoc.indexOf("&db=");
	if (pathLoc > -1){
		newLoc = curLoc.substring(0, pathLoc);
		pathLoc = curLoc.indexOf("&", pathLoc + 1);
		if (pathLoc == -1){
			newLoc = newLoc + "&db=" + newPath;
		} else {
			newLoc = newLoc + curLoc.substring(pathLoc) + "&db=" + newPath;
		}
	} else {
		newLoc = curLoc + "&db=" + newPath;
	}
	window.location=newLoc;
}

function checkForBackspace(curVal, key){
	//alert("checkForBackspace");
	if (key == "8"){
		setTimeout("doSearch();", 100);
	}
}

function doKeyPress(curVal, key) {
	//alert("doKeyPress");
	if(key =="13") {
		/* var trName = document.getElementById("nameChoicesTable").getElementsByTagName("tr")[0];
		if (trName.name){
			uName = trName.name;
		} else {
			uName = trName.className.substring(trName.className.indexOf(" ") + 1);
		}
		storeValue(uName); */
		return false;
	} else {		
		setTimeout("doSearch();", 100);
	}
}

function loadFirstPage() {
	try {
		// initialize variables
		var urlArray = document.location.href.split("/");

		URLPrefix = urlArray[0] + "//" + urlArray[2];

		// check to see if any parameters are being overridden from QueryString
		if (getURLParam("db") != "")
			dbPath = getURLParam("db");
		if (getURLParam("view") != ""){
			view = getURLParam("view");
		} else {
			view = "($VIMPeopleByLastName)"
		}
		if (getURLParam("columns") != ""){
			columns = getURLParam("columns").split(",");
		} else {
			columns = "0,2,3,5";
			columns = columns.split(",");
		}
		if (getURLParam("count") != ""){
			count = parseInt(getURLParam("count"), 10);
		} else {
			count = "16";
		}
		if (getURLParam("returnfield"))
			returnFieldName = getURLParam("returnfield");
		if (getURLParam("returncol") != "") {
			returnColumn = parseInt(getURLParam("returncol"), 10);
		} else {
			returnColumn = "1";
		}
		//alert(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&count=" + count);
		// get initial data set
		//var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&count=" + count, true);
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function nextPage() {
	try {
		// work out where the next page starts
		alert("step: 1");
		var lastMax = parseInt(results[results.length - 1].attributes[0].value, 10);
		alert("step: 2");
		var start = lastMax + 1;
		alert("step: 3");
		if (start > (viewTotalDocs - (count - 1))){
			alert("step: 4");
			start = viewTotalDocs - (count - 1);
		}
		// get the next page
		alert("step: 5");
		var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&start=" + start + "&count=" + count);
		alert("step: 6");
	}
	catch (e) {
		alert("step: 7");
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function previousPage() {
	try {
		// work out where the previous page starts
		var lastMin = parseInt(results[0].attributes[0].value, 10);
		var start = lastMin - count;
		if (start < 1) {
			start = 1;
		}
		// get the previous page
		var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&start=" + start + "&count=" + count);
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function lastPage() {
	try {
		// work out where the last page starts
		start = viewTotalDocs - (count - 1);

		// get the next page
		var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&start=" + start + "&count=" + count);
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function doSearch() {
	//alert("doSearch");
	try 	{
		var returnfield = getURLParam("returnfield");
		//alert("returnfield:" + returnfield);
		var pageNum = getURLParam("pageNum");
		//alert("pageNum:" + pageNum);
		var search = document.getElementById("search").value;
		//alert("search:" + search);
		if (search != "") {
			//var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&startkey=" + escape(search) + "&count=" + count);
			parent.location='/utils/contact_p.jsp?returnfield=' + returnfield + '&pageNum=' + pageNum + '&search=' + search;			
		} else {
			//var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&startkey=a&count=" + count);
		}
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function storeValue(newValue) {
	try {
		/* alert("newValue: " + newValue);
		alert("returnFieldName: " + returnFieldName);
		alert("fieldReturn.value: " + fieldReturn.value); */
		var fieldReturn = window.opener.document.getElementById(returnFieldName);
		if (fieldReturn == null){
			fieldReturn = eval("window.opener.document.forms[0]." + returnFieldName);
		}
		if (fieldReturn) {
			if (fieldReturn.type == "text" || fieldReturn.type == "hidden" || fieldReturn.type == "textarea") {
				fieldReturn.value = unescape(newValue);
			} else {
				fieldReturn.length = 1;
				var strReturn = unescape(newValue);
				fieldReturn.options[0].text = strReturn;
				fieldReturn.options[0].value = strReturn;
				fieldReturn.options[0].selected = true;
			}
		} else {
			throw("Could not get field \"" + returnFieldName + "\"");
		}
	}
	catch (e) {
		alert("There has been an error returning the selected values:\n\n" + e.message);
	}
	window.close();
}

function displayData(xmlDoc) {
	// get areas which we are going to write results into
	var namelist = document.getElementById("namelist");
	var countlist = document.getElementById("countlist");

	try {
		namelist.innerHTML = "Please Wait...";

		//Open the XML Document
		var root = xmlDoc.documentElement;
		results = root.getElementsByTagName("viewentry");

		//Get the toplevelentries value each time in case it changes
		viewTotalDocs = parseInt(root.attributes[0].value, 10);

		var strHTML = "<table width=\"100%\" id=\"nameChoicesTable\">";
		for (i=0; i<results.length; i++) {
			//Get the value which the row will return if clicked
			var returnText = getInnerText(results[i].getElementsByTagName("entrydata")[returnColumn]);

			//Write the tr tag
			if (i % 2 == 0){
				strHTML += "<tr class=\"normal1 " + escape(returnText) + "\" onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal1'\" name=" + escape(returnText) + " onClick=\"storeValue('" + escape(returnText) + "');\">";
			} else {
				strHTML += "<tr class=\"normal2 " + escape(returnText) + "\" onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal2'\" name=" + escape(returnText) + " onClick=\"storeValue('" + escape(returnText) + "');\">";
			}
			for (iCol=0; iCol < columns.length; iCol++) {
				//Write each cell of the current row
				var text;
				try {
					text = getInnerText(results[i].getElementsByTagName("entrydata")[parseInt(columns[iCol], 10)]);
				}
				catch (e) {
					text =+ e. message + " (" + e.name + ")";
				}
				strHTML += "<td>" + text + "</td>";
			}
			strHTML += "</tr>";
		}
		strHTML += "</table>";

		// output the document count details
		countlist.innerHTML = results[0].attributes[0].value + " to " + results[results.length - 1].attributes[0].value + " of " + viewTotalDocs + " records";

		// output the table HTML
		namelist.innerHTML = strHTML;
	}
	catch (e) {
		namelist.innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function doXMLHTTPGet(vurl) {
	var returnData = null;

	if (window.XMLHttpRequest) {
		// we are in a non-IE browser
		httpObj=new XMLHttpRequest()
	} else if (window.ActiveXObject) {
		// we are in IE
		httpObj=new ActiveXObject("Microsoft.XMLHTTP")
	}

	// return the XML document when it has finished loading
	httpObj.onreadystatechange = function() {
			if (httpObj.readyState==4) 	{
				if (httpObj.status==200) {
					displayData(httpObj.responseXML);
				} else 	{
					alert("Problem retrieving XML data:" + httpObj.statusText)
				}
			}
		}

	//Request the XML document
	httpObj.open("GET",vurl,true)
	httpObj.send(null)
}
/*
	getInnerText function courtesy of Martin Honnen
	http://www.thescripts.com/forum/threadedpost582930.html
*/
function getInnerText (node) {
	if (typeof node.textContent != 'undefined') {
		return node.textContent;
	} else if (typeof node.innerText != 'undefined') {
		return node.innerText;
	} else if (typeof node.text != 'undefined') {
		return node.text;
	} else {
		switch (node.nodeType) {
			case 3:
				break;
			case 4:
				return node.nodeValue;
				break;
			case 1:
				break;
			case 11:
				var innerText = '';
				for (var i = 0; i < node.childNodes.length; i++)
				{
					innerText += getInnerText(node.childNodes[i]);
				}
				return innerText;
				break;
			default:
				return '';
		}
	}
}
/*
	More on this function can be found at
	http://www.fclonline.com/Articles/GetURLParameterinJavascri.html
*/
function getURLParam(strParamName) {
	//Get a URL Parameter from the current location.href
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ){
		//var strQueryString = "&" + strHref.substr(strHref.indexOf("?") + 1).toLowerCase();
		var strQueryString = "&" + strHref.substr(strHref.indexOf("?") + 1)
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}
// -->
</script>

<script language="JavaScript" type="text/javascript">
<!-- 
document._domino_target = "_self";
function _doClick(v, o, t, h) {
  var form = document._NABPickerSingle;
  if (form.onsubmit) {
     var retVal = form.onsubmit();
     if (typeof retVal == "boolean" && retVal == false)
       return false;
  }
  var target = document._domino_target;
  if (o.href != null) {
    if (o.target != null)
       target = o.target;
  } else {
    if (t != null)
      target = t;
  }
  form.target = target;
  form.__Click.value = v;
  if (h != null)
    form.action += h;
  form.submit();
  return false;
}
// -->
</script>


</head>
<body onload="loadFirstPage();">
	<form method="post"
		action="/contact.jsp?OpenForm&amp;Seq=1&amp;returnfield=txtExecutiveSpon"
		name="_NABPickerSingle">
		<input type="hidden" name="__Click" value="0">
		<!--

Based on the NAB picker first written by Matt White of Fynn Consulting Ltd (portions Copyright 2005 Fynn Consulting Ltd), v1.0, 15-Aug-2005 (Initial Release). Modified for enhanced functionality by Scott Good of  Teamwork Solutions, Inc. (http://www.notesworkflow.com) Portions copyright 2005 Teamwork Solutions, Inc.


This page is designed to browse a Notes/Domino view to allow the user to pick single values from the view and return it to a text field.
If this page is loaded with no parameters it will try to open the ($VIMPeople) view in the names.nsf of the local server.
URL Parameters which can be added are:
	- &db=			the database to open
	- &view=		the view to open
	- &columns=	the list of columns to display to the user. They will be displayed in the order specified. Columns must be comma separated
	- &count=		the number of documents to return per page
	- &returnfield	the name of the field to return selected value to
					(only valid if this window is opened as a popup, if this is a modaldialog, the returnValue is set)
	- &returncol	the column which contains the value which will be returned
Written by: 		Matt White
Copyright:		Fynn Consulting Ltd
Version:		v1.0	15-Aug-2005		Initial Release
Modified for Domino by Teamwork Solutions, Inc. (http://www.notesworkflow.com) Portions copyright 2005 Teamwork Solutions, Inc.
-->

		<script language="javascript">
			/*
			 Configuration parameters which can be overridden
			 */
			var dbPath = "names.nsf"; //The default database to be used (can be overridden with the URL Param "db", e.g. "...html?db=mydir/mydb.nsf")
			var view = "($VIMPeople)"; //The default view to be used (can be overridden with the URL Param "view", e.g. "...html?view=myview")
			var columns = new Array("1", "2", "3", "0"); //The default columns which will be returned, and the order they will be displayed in
			//Can be overridden with the URL Param "columns" e.g. "...html?columns=1,2,3,4)
			var count = 10; //The default number of documents to return per page (can be overridden with the URL Param "count", e.g. "...html?count=20)
			var returnFieldName = null; //The fieldname which the selected value will be returned to (must be a plain text or textarea field)
			var returnColumn = 0; //The column from the view which will be returned to the returnFieldName
			/*
			 Global Variables
			 */

			var namesPicked = false;
			var results; // stores the xml returned from the view
			var viewTotalDocs; // stores the total number of docs in the view
			var URLPrefix; // stores the protocol and hostname (e.g. http://myhost)
			var aValues = new Array() // array of values to be written back
			var httpObj; // stores the XMLHTTPRequest
			var errormessage = "There has been an error displaying the data:<$tag_";
			// stores the error message prefix
			// Catch the user pressing return to submit searches

			if (!document.all) {
				window.captureEvents(Event.KEYPRESS);
				window.onkeypress = doKeyPress;
			}
		</script>
		<style type="text/css">
body,td {
	font-family: Arial, Arial, Helvetica, sans-serif;
	font-size: 8pt;
	background: #D5D5D5;
	border-bottom: thin;
	border-bottom-color: #DDDDDD;
}

tr {
	background-color: white;
}

.initial {
	background-color: white;
	color: black;
}

td.nextPrevButtons {
	width: 60px;
}

tr.normal1 td {
	background: #efefef;
}

tr.normal2 td {
	background: white;
}

.highlight {
	background-color: #316AC5;
	color: white;
	cursor: pointer;
}

input,select {
	font: 8pt Arial, Arial, sans-serif;
	border-color: silver;
	border-style: solid;
	border-width: 1px;
	font-size: 8pt;
}

.button {
	font: 8pt Arial, Arial, sans-serif;
	padding: 1px 2px;
	background: #efefef;
	color: black;
	font-weight: normal;
}

hr {
	height: 1px;
	color: #DDDDDD;
}

.okButtn,.cancelButtn {
	width: 60px;
}

td#okCancelArea {
	text-align: right;
	border-top: 1pt silver solid;
	padding-top: 8px;
}

td#removeAllArea {
	text-align: center;
}

td input.removeAll {
	width: 150px;
}

#search {
	position: absolute;
	top: 32px;
	right: 11px;
	width: 200px;
	height: 20px;
}

#topBar td {
	padding-bottom: 6px;
}

#storedlist,#namelist {
	border: solid 1px silver;
	background: white;
}

#addrBookPicker {
	position: absolute;
	top: 10px;
	right: 11px;
}

td.labels {
	padding: 0 0 5px 0;
}
</style>

		<div align="center">
			<table width="100%" border="0">
				<tr>
					<td align="left" width="100%" class="labels">From... <input
						name="%%Surrogate_AddressBook" type="hidden" value="1"> <select
						name="AddressBook"
						onchange="changeNab(this.options[this.selectedIndex].value);
		
"
						id="addrBookPicker">
							<option value="names.nsf">Celestica Google's Address Book
					</select>

					</td>
				</tr>
				<tr id="topBar">
					<td align="left" width="100%" class="labels">Search for... <input
						name="search" id="search" onFocus="select();"
						onKeyUp="checkForBackspace(this.value, (event.which) ? event.which : window.event.keyCode);"
						onKeyPress="return doKeyPress(this.value, (event.which) ? event.which : window.event.keyCode);"
						value="<%=request.getParameter("search")%>" />
					</td>

				</tr>
				<tr>
					<td id="namelist" valign="top">
						<table width="100%">
							<%
								String domain = "celestica.com";
								String admin_username = "appengine01-cls@celestica.com";
								String admin_password = "good4clstesting";
								String gusername = "syoudee@celestica.com";
								
								String APPS_FEEDS_URL_BASE = "https://apps-apis.google.com/a/feeds/";
								String SERVICE_VERSION = "2.0";
								String domainUrlBase = APPS_FEEDS_URL_BASE + domain + "/";
								UserFeed ufeed;
								
								int maxContactPage = 16;
								int maxContactPageReturn = 0;
								String search = "";
								int pageNum = 1;
								int nextPage = 1;
								int lastPage = 1;
								int prevPage = 1;
								int startIndex = 1;
								int endIndex = maxContactPage;
								String userName = "";
								String fullName = "";
								String eMail = "";
								String fullName_rev = "";
								
								if (request.getParameter("pageNum") != null) {
									pageNum = Integer.parseInt(request.getParameter("pageNum"));
								}
								if (pageNum > 1) {
									startIndex = (maxContactPage * (pageNum - 1)) + 1;
									endIndex = pageNum * maxContactPage;
									prevPage = pageNum - 1;
								}								
								String countPage = "";
								String showTemp = "";								
								try {
									String getContactURL = "";	
									String emailAddress = "";
									if (request.getParameter("search") != null) {
										search = request.getParameter("search");	
									}									

									int j = 0;
									AppsForYourDomainClient client = new AppsForYourDomainClient(admin_username, admin_password, domain);
									ufeed = client.retrieveAllUsers();
									String strCSSNormal1 = "normal1";
									String strCSSNormal2 = "normal2";
									String strCSSHighlight = "highlight";
									String strClass = strCSSNormal1;	
									maxContactPageReturn = ufeed.getEntries().size();
									if (endIndex > maxContactPageReturn) {
										endIndex = maxContactPageReturn;									
									}
									if (search.length() > 0) {
										search = search.toLowerCase();
										startIndex = 1;
										endIndex = maxContactPageReturn;
									}
									for (int i = (startIndex - 1); i < (ufeed.getEntries().size()) & (i <= endIndex); i++) {
										UserEntry entry = ufeed.getEntries().get(i);
										if (search.length() == 0) {											
											userName = entry.getTitle().getPlainText().toLowerCase().trim();
											fullName = entry.getName().getGivenName().toString().trim() + " " + entry.getName().getFamilyName().toString().trim();
											eMail = userName + "@" + domain;
											fullName_rev = entry.getName().getFamilyName().toString().trim() + " " + entry.getName().getGivenName().toString().trim();
										} else {
											userName = entry.getTitle().getPlainText().toLowerCase().trim();
											fullName = entry.getName().getGivenName().toLowerCase().trim() + " " + entry.getName().getFamilyName().toLowerCase().trim();
											eMail = userName + "@" + domain;
											fullName_rev = entry.getName().getFamilyName().toLowerCase().trim() + " " + entry.getName().getGivenName().toLowerCase().trim();
											if ((userName.indexOf(search) >= 0) | (fullName.indexOf(search) >= 0) | (eMail.indexOf(search) >= 0) | (fullName_rev.indexOf(search) >= 0)) {
												userName = entry.getTitle().getPlainText().toLowerCase().trim();
												fullName = entry.getName().getGivenName().toString().trim() + " " + entry.getName().getFamilyName().toString().trim();
												eMail = userName + "@" + domain;
											} else {
												userName = "";
												fullName = "";
												eMail =  "";																							
											}
										}
										if (userName.length() > 0) {
											if (j % 2 == 0){
												strClass = strCSSNormal1;
											} else {
												strClass = strCSSNormal2;
											}																		
											out.println("<tr class=\"" + strClass + "\" onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='" + strClass + "'\" onClick=\"storeValue('" + eMail + "');\">");
											out.println("<td>");
											out.println(userName);
											out.println("</td>");
											out.println("<td>");
											out.println(fullName);
											out.println("</td>");
											out.println("</tr>");
											j++;
										}										
									}
									if ((search.length() > 0)) {										
										if (j > 0) {
											startIndex = 1;	
											endIndex = j;
										} else {
											startIndex = 0;
											endIndex = 0;
										}										
									}
									nextPage = pageNum + 1;
									NumberFormat formatter = new DecimalFormat("0");
									double dmaxResultReturn = Double.parseDouble(String.valueOf(maxContactPageReturn));
									double dmagResultPage = Double.parseDouble(String.valueOf(maxContactPage));
									double dResultPageTemp = Math.ceil(dmaxResultReturn / dmagResultPage);									
									lastPage = Integer.parseInt(formatter.format(dResultPageTemp));									
								} catch (Exception ee) {
									System.out.println( "Error : " + ee.toString() );
									countPage = ee.toString();
								}
								countPage = String.valueOf(startIndex) + " to " + String.valueOf(endIndex) + " of " + String.valueOf(maxContactPageReturn);
								//showTemp = "startIndex:" + startIndex + "|endIndex:" + endIndex + "|pageNum:" + pageNum + "|prevPage:" + prevPage + "|nextPage=" + nextPage + "|lastPage:" + lastPage + "|search" + search;
							%>
						</table>
					</td>

				</tr>
				<tr>
					<td>
						<table width="100%">
							<tr>
								<td align="right" class="nextPrevButtons"><input
									type="button" class="button" value="|<" onClick="parent.location='/utils/contact_p.jsp?returnfield=<%=request.getParameter("returnfield")%>&pageNum=1&search='" />
									<input type="button" class="button" value="<" onClick="parent.location='/utils/contact_p.jsp?returnfield=<%=request.getParameter("returnfield")%>&pageNum=<%=prevPage%>&search='" />
								</td>
								<td align="center" id="countlist"><%=countPage%>   <%=showTemp%></td>
								<td align="left" class="nextPrevButtons"><input
									type="button" class="button" value=">" onClick="parent.location='/utils/contact_p.jsp?returnfield=<%=request.getParameter("returnfield")%>&pageNum=<%=nextPage%>&search='" />
									<input type="button" class="button" value=">|"
									onClick="parent.location='/utils/contact_p.jsp?returnfield=<%=request.getParameter("returnfield")%>&pageNum=<%=lastPage%>&search='" /></td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td id="okCancelArea"><input type="button"
						class="button okButtn" value="OK" onClick="storeValue(true);" />
						<input type="button" class="button cancelButtn" value="Cancel"
						onClick="window.close();" /></td>
				</tr>
			</table>
		</div>
		<script>
			document.getElementById("search").focus();
		</script>
	</form>
</body>
</html>